#include "SConfig.h"
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include "trim.h"
#include <string>
#include <stdlib.h>

void SConfig::get_key_value(Conf_info *confd,char* text)
{
	char* str = strchr(text,'=');
	confd->value = new char[strlen(str)+1];
	strcpy(confd->value,str+1);
	confd->value[strlen(str)] = '\0';
	trim(confd->value);
	int n = strlen(text)-strlen(confd->value)-1;
	confd->key = new char[n];
	strncpy(confd->key,text,n);
	confd->key[n] = '\0';
	trim(confd->key);
	printf("confd->key : %s\n",confd->key);
	printf("confd->value : %s\n",confd->value);
	putchar('\n');
}
bool SConfig::ParesFile(const char* file)
{
	FILE *fd = fopen(file,"r");
	char buf[1024];
	//int conf_num = 0;
	while(fgets(buf,sizeof(buf),fd))
	{
		trim(buf);
		Conf_info confd;
		if(buf[0]=='\n'||buf[0]=='#'||buf[0]==';')
		{
			continue;
		}
		if(strchr(buf,'=') == 0)
		{
			continue;
		}
		printf("buf:%s\n",buf);
		get_key_value(&confd,buf);
		clist.push_back(confd);
				
	}
	fclose(fd);
	return true;
}
void SConfig::print_conf()
{
	int i;
	for(i = 0; i < clist.size();i++)
	{
		printf("key:%s,value:%s\n",this->clist[i].key,this->clist[i].value);
	}
}
SConfig::~SConfig()
{
	vector<Conf_info>::iterator it;	
	for(it = clist.begin(); it != clist.end();it++)
	{
		delete [](*it).key;
		delete [](*it).value;
	}

}
bool SConfig::GetConfigString(const char *key,char** str)
{
	int i;
	for(i = 0;i < clist.size();i++)
	{
		if(strcmp(clist[i].key,key)==0)
		{
			*str = clist[i].value;
			//printf("this key's value is %s",clist[i].value);
			break;
		}
	}
	if(i == clist.size())
	{
		return false;
	}
	return true;
}
bool SConfig::GetConfigInt(const char *key,int &val)
{
	int i;
	for(i = 0;i < clist.size();i++)
	{
		if(strcmp(clist[i].key,key)==0)
		{
			val = atoi(clist[i].value);
			//printf("this key's value is %s",clist[i].value);
			break;
		}
	}
	if(i == clist.size())
	{
		return false;
	}
	return true;
}
bool SConfig::GetConfigFloat(const char *key,float &val)
{
	int i;
	for(i = 0;i < clist.size();i++)
	{
		if(strcmp(clist[i].key,key)==0)
		{
			val = atof(clist[i].value);
			//printf("this key's value is %s",clist[i].value);
			break;
		}
	}
	if(i == clist.size())
	{
		return false;
	}
	return true;
}
